package com.zhc.dejingapi.utils.ding;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
import com.zhc.dejingapi.pojo.dingtalk.DingTalkApiInfo;

import java.util.Date;

public class DingAccessTokenUtils {


    private static String _DingAccessToken;
    private static Date _DingExpireDate;

    /**
     * 通过调用接口获取access_token
     * dingtalk
     * @return
     * String
     * 2021-1-20
     */
    public static String getAccessToken(DingTalkApiInfo dingTalkApiInfo) {
        boolean IsNeedReget=false;
        if (_DingAccessToken==null||_DingAccessToken.isEmpty()){
            IsNeedReget=true;
        }else if (_DingExpireDate!=null&&_DingExpireDate.before(new Date())){
            IsNeedReget=true;
        }

        if(IsNeedReget){
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(dingTalkApiInfo.getAppKey());
            request.setAppsecret(dingTalkApiInfo.getAppSecret());
            request.setHttpMethod("GET");
            OapiGettokenResponse response = null;
            try {
                response = client.execute(request);
                _DingAccessToken=response.getAccessToken();
                long  lExpireIn= response.getExpiresIn();
                lExpireIn-=5;
                lExpireIn*=1000;
               // _DingExpireDate=new Date(response.getExpiresIn()*1000-10000+System.currentTimeMillis());
                _DingExpireDate=new Date(lExpireIn+System.currentTimeMillis());
            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return _DingAccessToken;
    }
}
